package systems 
{
	import systems.events.CollisionEvent;
	/**
	 * @author Humberto Anjos
	 */
	public class Collisions 
	{
		private var _main:Main
		public function Collisions(main:Main) 
		{
			_main = main
			
			EventChannel.INSTANCE.addEventListener(CollisionEvent.SHIP_AND_ENEMY, onShipAndEnemy, false, 0, true)
			EventChannel.INSTANCE.addEventListener(CollisionEvent.SHIP_AND_BULLET, onShipAndBullet, false, 0, true)
			EventChannel.INSTANCE.addEventListener(CollisionEvent.ENEMY_AND_BULLET, onEnemyAndBullet, false, 0, true)
		}
		
		public function update() :void
		{
			var objects = _main.world.objects
			
			for (var i = 0; i < objects.length - 1; i++) {
				var left = objects[i]
				for (var j = i + 1; j < objects.length; j++) {
					var right = objects[j]
					
					if (left.hitTestObject(right)) {
						if (left is Ship && right is Enemy) {
							EventChannel.INSTANCE.dispatchEvent(new CollisionEvent(CollisionEvent.SHIP_AND_ENEMY, left, right))
						} else if (left is Enemy && right is Ship) {
							EventChannel.INSTANCE.dispatchEvent(new CollisionEvent(CollisionEvent.SHIP_AND_ENEMY, right, left))
						} else if (left is Ship && right is Bullet) {
							EventChannel.INSTANCE.dispatchEvent(new CollisionEvent(CollisionEvent.SHIP_AND_BULLET, left, right))
						} else if (left is Bullet && right is Ship) {
							EventChannel.INSTANCE.dispatchEvent(new CollisionEvent(CollisionEvent.SHIP_AND_BULLET, right, left))
						} else if (left is Enemy && right is Bullet) {
							EventChannel.INSTANCE.dispatchEvent(new CollisionEvent(CollisionEvent.ENEMY_AND_BULLET, left, right))
						} else if (left is Bullet && right is Enemy) {
							EventChannel.INSTANCE.dispatchEvent(new CollisionEvent(CollisionEvent.ENEMY_AND_BULLET, right, left))
						}
					}
				}
			}
		}
		
		private function onShipAndEnemy(e:CollisionEvent):void
		{
			//_main.world.destroyEnemy(e.right as Enemy)
			_main.world.destroyShip()
		}
		
		private function onShipAndBullet(e:CollisionEvent):void
		{
			trace("ship:", e.left as Ship, "bullet:", e.right as Bullet)
		}
		
		private function onEnemyAndBullet(e:CollisionEvent):void
		{
			var bullet:Bullet = e.right as Bullet;
			var enemy:Enemy = e.left as Enemy;
			
			if(enemy.state === bullet.state) {
				_main.world.destroyEnemy(enemy)
				_main.world.destroyBullet(bullet)
			}
		}
	}

}